package uia.alumni.group;

import java.io.IOException;
import javax.annotation.Resource;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.PersistenceUnit;
import javax.persistence.Query;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import javax.transaction.UserTransaction;
import uia.alumni.data.Group;
import uia.alumni.data.Role;
import uia.alumni.data.User;
import uia.alumni.web.Command;

import static uia.alumni.web.Constants.*;

/**
 * This class is used to Join a Group.
 * @author Simon Zimmermann
 */
public class JoinGroup extends Command {

    public static final String SERVLET_NAME = "group.join";
    public final static long serialVersionUID = 1;

    @PersistenceUnit(name = PERSISTENCE_UNIT)
    private EntityManagerFactory emf;

    @Resource
    private UserTransaction tx;

    public JoinGroup() {
        super(Role.member);
    }

    @Override
    public void execute(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        EntityManager em = emf.createEntityManager();
        boolean success = false;

        try {
            Group group = getGroup(em, request);
            User user = getLoggedInUser(em, request);

            if (group != null && user != null) {
                tx.begin();
                em.joinTransaction();
                group.joinGroup(user, Role.member);
                em.persist(group);
                tx.commit();
            } else {
                addMessage(request, "Something went Wrong!");
            }
        } catch (Exception e) {
            addMessage(request, e.getMessage());
        } finally {
            em.close();
            forwardTo(ViewGroup.SERVLET_NAME, request, response);
        }
    }
}
